package com.tq68.weixin.controller.login;

import java.util.Date;

import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.tq68.weixin.common.AppConstantEnum;
import com.tq68.weixin.model.Checkin;
import com.tq68.weixin.model.CommunityAlias;
import com.tq68.weixin.model.User;
import com.tq68.weixin.model.UserCommunity;
import com.tq68.weixin.rules.ContributionValueRank;
import com.tq68.weixin.utils.DateUtils;
import com.tq68.weixin.utils.MD5;
import com.tq68.weixin.vo.UserVO;

public class LoginController extends ApiController {

	public void index(){
		String code = getPara("code");
		String action = getPara("action");
		Integer selleridFromScan = 0;
		if(action.indexOf("_")>-1){//带有扫码带过来的商家id
			String[] actions = action.split("_");
			action = actions[0];
			selleridFromScan = Integer.parseInt(actions[1]);
		}
		System.out.println("action="+action);
		System.out.println("selleridFromScan="+selleridFromScan);
		SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(PropKit.get("appId"), PropKit.get("appSecret"), code);
		ApiResult apiResult = SnsApi.getUserInfo(accessToken.getAccessToken(), code);
		//用户昵称
		String nickname = apiResult.get("nickname");
		//用户的唯一标识
		String openid = apiResult.get("openid");
		//用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），
		//用户没有头像时该项为空。若用户更换头像，原有头像URL将失效。
		String usericon = apiResult.get("headimgurl");
		//用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
		Integer sex = apiResult.get("sex");
		User user = User.dao.getUserByWeixinOpenid(openid);
		UserVO vo = new UserVO();
		removeSessionAttr("sellervo");
		//已定位过，有小区记录
		if(user!=null && user.getUserCommId()!=null){
			vo.setUserid(user.getId());
			vo.setNickname(user.getNickname());
			vo.setOpenid(openid);
			vo.setUserCommunityId(user.getUserCommId());
			vo.setUserCommunityName(user.getUserCommName());
			vo.setCommunityNameAlias(CommunityAlias.dao.getCommunityAlias(user.getUserCommId()));
			vo.setUsericon(usericon);
			vo.setPhone(user.getPhone());
			vo.setUsername(user.getUsername());
			vo.setUserlevel(user.getUserlevel());
			vo.setUserlevelStr(AppConstantEnum.UserLevel.codeMap.get(user.getUserlevel()+""));
			vo.setLevelColor(user.getUserlevel());
			vo.setCoins(user.getGoldcoin());
			vo.setCvalue(user.getContributionValue());
			vo.setHomeTown(user.getHomeTown());
			vo.setProvince();
			vo.setCity();
			vo.setDistin();
			vo.setSex(user.getSex());
			vo.setIsRealName(user.getIsRealName());
			vo.setSelleridFromScan(selleridFromScan);
			vo.setSameHometownCount(User.dao.getUserCountByHometownAndCommid(user.getHomeTown(), user.getUserCommId()));
			vo.setLastCheckinDate(user.getLastCheckinDate());
			vo.setCheckinToday(DateUtils.toDateStr(new Date()).equals(user.getLastCheckinDate())?true:false);
			//user.getUserCommId()：用户表的，小区id； vo.getUsercommid：VO的，用户与小区关联的id
			vo.setUsercommid(UserCommunity.dao.findUcByUseridCommid(user.getId(),user.getUserCommId()).getId());
			vo.setRecentlyChecklist(Checkin.dao.getResentlyCheckRecord(vo.getUsercommid()));
			setSessionAttr("uservo", vo);
			//当天第一次登录时，计算贡献值，并更新最后登录时间
			if(!DateUtils.toDateStr(new Date()).equals(user.getLastLoginDate())){
				user.setLastLoginDate(DateUtils.toDateStr(new Date()));
				user.update();
				ContributionValueRank cv = new ContributionValueRank();
				cv.loginSuccess(user.getId());
			}
			if("2".equals(action)){
				redirect("/discounts");
			}else if("1".equals(action)){
				redirect("/checkin");
			}else{
				redirect("/communityChat");
			}
		}else{
			//新关注的用户，新增绑定，只要关注了就存入库，或未完成接入向导的用户再次进入
			if(user==null){
				//新关注的用户，新增绑定，只要关注了就存入库
				user = new User();
				user.setNickname(nickname);
				//密码默认6个8
				String passwd = "888888";
				try{
					passwd = MD5.encrypt(passwd);
				}catch(Exception e){
					e.printStackTrace();
				}
				user.setPassword(passwd);
				user.setUsericon(usericon);
				user.setWxOpenid(openid);
				user.setWxNickname(nickname);
				user.setUserlevel(Integer.parseInt(AppConstantEnum.UserLevel.Visitor.getCode()));
				//暂时默认为openid的前10位
				user.setUsername(openid.substring(0, 10));
				user.setLastLoginDate(DateUtils.toDateStr(new Date()));
				user.setSex(sex);
				user.save();
			}
			//存入session
			vo.setUserid(user.getId());
			vo.setNickname(nickname);
			vo.setOpenid(openid);
			vo.setUserCommunityName("未定位小区");
			vo.setUsericon(usericon);
			vo.setUsername(user.getUsername());
			vo.setUserlevel(user.getUserlevel());
			vo.setUserlevelStr(AppConstantEnum.UserLevel.codeMap.get(user.getUserlevel()+""));
			vo.setSelleridFromScan(selleridFromScan);
			setSessionAttr("uservo", vo);
			redirect("/newuser");
		}
	}
	
	@Override
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
}
